package org.wk.affiliate.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Service;
import org.wk.affiliate.dao.NotifyDao;
import org.wk.affiliate.domain.Notify;
import org.wk.affiliate.view.NotifyVo;
import org.wk.common.jpush.PushService;
import org.wk.common.view.SysNoticeDTO;
import org.wk.core.common.view.ResponseVo;
import org.wk.user.dao.UserDao;
import org.wk.user.domain.User;

import java.util.*;

/**
 * @author TangShenShen
 * @Description: 通知服务实现类
 * @date 2018/6/12 14:07
 */
@Service
public class NotifyServiceImpl implements NotifyService{

    @Autowired
    private UserDao userDao;
    @Autowired
    private PushService pushService;
    @Autowired
    private NotifyDao notifyDao;

    /*
     * @description 发送通知并且保存
     * @param
     * @author ZhaoPing'an
     * @date 2018/7/9 16:28
     */
    @Override
    public void saveAndSendPush(NotifyVo notifyVo) {
        String[] userIds = notifyVo.getUserIds();				// 用户的id集合
        String notifyTitle = notifyVo.getNotifyTitle();  		// 通知标题
        String notifyContent = notifyVo.getNotifyContent();  // 通知内容
        boolean isAllUser = notifyVo.isAllUserFlag(); 			// 是否选择全部用户
        List<String> ids = new ArrayList<>();
        if (isAllUser) {
            List<User> users = userDao.findAll();
            for (User user: users) {
                ids.add(user.getId());
            }
        }else {
            ids = Arrays.asList(userIds);
        }
        // 保存通知
        Notify entity = new Notify();
        BeanUtils.copyProperties(notifyVo,entity);
        entity.setTargetUsers(Arrays.toString(userIds));
        notifyDao.save(entity);
        // 发送通知
        Map<String,String> pushExt = new HashMap<>();
        SysNoticeDTO sysNoticeDTO = new SysNoticeDTO();
        sysNoticeDTO.setTitle(notifyTitle);
        sysNoticeDTO.setContent(notifyContent);
        pushExt.put("content",JSONObject.toJSONString(sysNoticeDTO));
        pushExt.put("content_type","sys_notice");
        pushService.pushNotification(notifyTitle,pushExt,ids);
    }
}
